package com.zjk.test;


import cn.hutool.core.io.FileUtil;
import com.zjk.storage.config.FileStorageProperties;
import com.zjk.storage.core.FileStorageService;
import com.zjk.storage.core.entity.BaseFileInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {

    private final FileStorageService fileStorageService;
    private final FileStorageProperties properties;

    @PostMapping("/upload")
    public BaseFileInfo upload(@RequestParam("file") MultipartFile file) {
        BaseFileInfo fileInfo = fileStorageService.of(file).setPlatform(properties.getDefaultPlatform()).upload();
        log.info("文件上传成功！fileInfo:{}", fileInfo);
        return fileInfo;
    }

    @PostMapping("/download")
    public void download(@RequestBody BaseFileInfo fileInfo, HttpServletResponse response) throws IOException {
        fileStorageService.download(fileInfo).outputStream(response.getOutputStream());
    }

    @PostMapping("/downloadToFile")
    public void downloadToFile(@RequestBody BaseFileInfo fileInfo) throws IOException {
        fileStorageService.download(fileInfo).inputStream(inputStream -> {
            FileUtil.writeFromStream(inputStream, new File("C:\\Users\\szyh_pc\\Desktop\\test\\download" + fileInfo.getFileName()));
        });
    }
}
